﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Pg.BioMedics.ASR.Client
{
    public partial class TaskResultsForm : Form
    {
        public TaskResultsForm()
        {
            InitializeComponent();
        }

        #region Event handlers

        private void resultsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (resultsComboBox.SelectedIndex != -1)
            {
                WebServices.Result result = (WebServices.Result)resultsComboBox.SelectedItem;

                if (result.TypeCode != "mpeg7")
                {
                    resultContainer.Panel1Collapsed = false;
                    resultContainer.Panel2Collapsed = true;
                    contentTextBox.Text = result.Content;
                }
                else
                {
                    resultContainer.Panel1Collapsed = true;
                    resultContainer.Panel2Collapsed = false;
                    
                    // save document in temp file
                    TempFile tempFile = new TempFile(result.Content);
                    contentWebBrowser.Navigate(tempFile.Location);
                }
            }
        }

        private void closeButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion

        #region Overriden methods

        public DialogResult ShowDialog(IWin32Window owner, WebServices.Result[] results)
        {            
            resultsBindingSource.DataSource = results;
            resultsComboBox.SelectedIndex = -1;

            return ShowDialog(owner);
        }

        #endregion                
    }

    internal class TempFile : IDisposable
    {
        private string _location;

        internal TempFile(string content)
        {
            _location = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
            File.WriteAllText(_location, content);
        }

        ~TempFile()
        {
            Dispose();
        }

        internal string Location
        {
            get
            {
                return _location;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_location != null)
            {
                if (File.Exists(_location))
                    File.Delete(_location);
            }
        }

        #endregion
    }
}
